package com.iotechn.unimall.app.api.active;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.core.exception.AppServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.domain.ActiveUserDO;
import com.iotechn.unimall.data.mapper.ActiveUserMapper;
import com.iotechn.unimall.data.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
public class ActiveUserServiceImpl implements ActiveUserService {
    @Autowired
    private ActiveUserMapper activeUserMapper;

    @Override
    public List<ActiveUserDO> list(Long activeId) throws ServiceException {
        Wrapper<ActiveUserDO> wrapper = new EntityWrapper<ActiveUserDO>();
        /**if (!StringUtils.isEmpty(name)) {
         wrapper.like("username", name);
         }**/
        wrapper.orderBy("id", false);
        List<ActiveUserDO> ActiveUserDOS = activeUserMapper.selectList(wrapper);
        return ActiveUserDOS;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActiveUserDO create(ActiveUserDO activeUserDO, Long userId) throws ServiceException {
        activeUserDO.setUserId(userId);
        Date now = new Date();
        activeUserDO.setGmtCreate(now);
        activeUserDO.setGmtUpdate(now);
        activeUserDO.setHeadUrl(SessionUtil.getUser().getAvatarUrl());
        if (activeUserMapper.insert(activeUserDO) > 0) {
            activeUserDO.setId(activeUserDO.getId());
            return activeUserDO;
        }
        throw new AppServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String delete(Long activeId, Long userId) throws ServiceException {
        Wrapper<ActiveUserDO> wrapper = new EntityWrapper<ActiveUserDO>();
        /**if (!StringUtils.isEmpty(name)) {
         wrapper.like("username", name);
         }**/

        wrapper.eq("active_id", activeId);
        wrapper.eq("user_id", userId);

        if (activeUserMapper.delete(wrapper) > 0) {
            return "ok";
        }
        throw new AppServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);

    }

}